package com.rr.graphql.resolver;

import com.netflix.graphql.dgs.*;
import com.rr.dto.Department;
import com.rr.dto.Employee;
import org.dataloader.DataLoader;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

/**
 * @author RR
 * @date 2023/6/11 17:26
 */
@DgsComponent
public class DepartmentQueryResolver {

    int index = 0;

    @DgsQuery
    public List<Department> departments() {
        List<Department> departmentList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Department department = new Department();
            department.setId(String.valueOf(index++));
            department.setName("软件工程   " + index);
            departmentList.add(department);
        }
        return departmentList;
    }

    @DgsQuery
    public Department department(String id) {
        Department department = new Department();
        department.setId(id);
        department.setName("软件工程");
        return department;
    }

    /**
     * 不用dataLoader，会有N+1问题
     */
//    @DgsData(parentType = "Department", field = "employees")
//    public List<Employee> employees(DgsDataFetchingEnvironment environment) {
//        Object source = environment.getSource();
//        return null;
//    }
    @DgsData(parentType = "Department", field = "employees")
    public CompletableFuture<List<Employee>> employees(DgsDataFetchingEnvironment environment) {
        DataLoader<String, List<Employee>> employeesLoader = environment.getDataLoader("employees");
        String id = ((Department) environment.getSource()).getId();
        return employeesLoader.load(id);
    }

}